package com.glowdayz.glowmee;

import java.io.IOException;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.drawable.StateListDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.glowdayz.common.ActivityManager;
import com.glowdayz.common.CDialog;
import com.glowdayz.common.XmlParser;

public class ProductFilter extends Activity implements OnItemSelectedListener, OnClickListener {
	
	private ActivityManager am = ActivityManager.getInstance();
	
	int paramId = 0;
	String paramFirst = null;
	String paramTitle = null;
	int paramTotal = 0;
	
	RadioGroup orderRadioGroup = null;
	Spinner spinnerFilter = null;
	int spinnerIndex = 0;
	EditText price1 = null, price2 = null;
	
	String[] brandArr = null;
	String[] keyWordArr = null;
	String[] paramKeyWordArr = null;
	boolean[] checked = null;
	String keyWord = null;
	
	LinearLayout keyWordLayout = null;
	
	int paramOrder = 0;
	String brandTitle = "";
	String paramPrice1 = "", paramPrice2 = "", paramKeyWord = "";
	
	RadioButton orderBt1 = null, orderBt2 = null, orderBt3 = null, orderBt4 = null, orderBt5 = null;
	
	boolean newFilter = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_product_filter);
		
		am.addActivity(this);
		
		ImageView backBt = (ImageView) findViewById(R.id.backBt);
		backBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77252525,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		backBt.setOnClickListener(new Button.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		ImageView okBt = (ImageView) findViewById(R.id.okBt);
		okBt.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().setColorFilter(0x77252525,PorterDuff.Mode.SRC_ATOP);
                        view.invalidate();
                        break;
                    }
                    case MotionEvent.ACTION_UP:
                    case MotionEvent.ACTION_CANCEL: {
                        ImageView view = (ImageView) v;
                        view.getDrawable().clearColorFilter();
                        view.invalidate();
                        break;
                    }
                }
                return false;
            }
        });
		okBt.setOnClickListener(this);
		
		TextView textTitle = (TextView) findViewById(R.id.textTitle);
		textTitle.setText("정렬옵션");
		
		Intent fromIntent = getIntent();
		paramId = fromIntent.getIntExtra("PARAM_id", 0);
		paramFirst = fromIntent.getStringExtra("PARAM_first");
		paramTitle = fromIntent.getStringExtra("PARAM_title");
		paramTotal = fromIntent.getIntExtra("PARAM_total", 0);
		
		paramOrder = fromIntent.getIntExtra("PARAM_order", 0);
		paramPrice1 = fromIntent.getStringExtra("PARAM_price1");
		paramPrice2 = fromIntent.getStringExtra("PARAM_price2");
		brandTitle = fromIntent.getStringExtra("PARAM_brand");
		paramKeyWord = fromIntent.getStringExtra("PARAM_keyWord");
		
		newFilter = fromIntent.getBooleanExtra("PARAM_newFilter", true);
		
		orderRadioGroup = (RadioGroup) findViewById(R.id.orderRadioGroup);
		
		spinnerFilter = (Spinner) findViewById(R.id.spinnerFilter);
		spinnerFilter.setPrompt("브랜드를 선택하세요.");
		spinnerFilter.setOnItemSelectedListener(this);
		
		price1 = (EditText) findViewById(R.id.price1);
		price2 = (EditText) findViewById(R.id.price2);
		
		keyWordLayout = (LinearLayout) findViewById(R.id.keyWordLayout);
		
		(new FilterWorker()).execute();
		
		orderBt1 = (RadioButton) findViewById(R.id.orderBt1);
		orderBt2 = (RadioButton) findViewById(R.id.orderBt2);
		orderBt3 = (RadioButton) findViewById(R.id.orderBt3);
		orderBt4 = (RadioButton) findViewById(R.id.orderBt4);
		orderBt5 = (RadioButton) findViewById(R.id.orderBt5);
		orderBt1.setOnClickListener(this);
		orderBt2.setOnClickListener(this);
		orderBt3.setOnClickListener(this);
		orderBt4.setOnClickListener(this);
		orderBt5.setOnClickListener(this);
		
		if (paramOrder > 0) {
			switch (paramOrder) {
			case 1:
				orderRadioGroup.check(R.id.orderBt2);
				orderBt2.setTextColor(Color.parseColor("#e63646"));
				orderBt1.setTextColor(Color.parseColor("#252525"));
				orderBt3.setTextColor(Color.parseColor("#252525"));
				orderBt4.setTextColor(Color.parseColor("#252525"));
				orderBt5.setTextColor(Color.parseColor("#252525"));
				break;
			case 2:
				orderRadioGroup.check(R.id.orderBt3);
				orderBt3.setTextColor(Color.parseColor("#e63646"));
				orderBt1.setTextColor(Color.parseColor("#252525"));
				orderBt2.setTextColor(Color.parseColor("#252525"));
				orderBt4.setTextColor(Color.parseColor("#252525"));
				orderBt5.setTextColor(Color.parseColor("#252525"));
				break;
			case 3:
				orderRadioGroup.check(R.id.orderBt4);
				orderBt4.setTextColor(Color.parseColor("#e63646"));
				orderBt1.setTextColor(Color.parseColor("#252525"));
				orderBt2.setTextColor(Color.parseColor("#252525"));
				orderBt3.setTextColor(Color.parseColor("#252525"));
				orderBt5.setTextColor(Color.parseColor("#252525"));
				break;
			case 4:
				orderRadioGroup.check(R.id.orderBt5);
				orderBt5.setTextColor(Color.parseColor("#e63646"));
				orderBt1.setTextColor(Color.parseColor("#252525"));
				orderBt2.setTextColor(Color.parseColor("#252525"));
				orderBt3.setTextColor(Color.parseColor("#252525"));
				orderBt4.setTextColor(Color.parseColor("#252525"));
				break;
			}
		}
		
		if (paramPrice1 != null) {
			price1.setText(paramPrice1);
		}
		if (paramPrice2 != null) {
			price2.setText(paramPrice2);
		}
		if (paramKeyWord != null) {
			paramKeyWordArr = paramKeyWord.split(",");
		}
	}
	
	public class FilterWorker extends AsyncTask<Object, String, Object> {
		@Override
		protected void onPreExecute() {
			CDialog.showLoading(ProductFilter.this);
		}
		
		@Override
		protected Object doInBackground(Object... params) {
			Object result = null;
			
			// 접속할 주소 정의
			String url = getResources().getString(R.string.server_url) + "/glowmee/productFilterXml.do?id=" + paramId;
			
			// XML 파서 생성
			XmlPullParser parser = XmlParser.getInstance().getParser(url);
			
			// 통신 실패시 예외처리
			if (parser == null) {
				this.cancel(true);
				return null;
			}
			
			String idBrandValue = null;
			int count = 1;
			
			try {
				String tag = null;
				int type = parser.getEventType();

				// 파싱 처리를 위한 반복 시작
				while (type != XmlPullParser.END_DOCUMENT) {
					// 읽은 태그의 이름
					tag = parser.getName();

					// 현재 읽고 있는 태그의 종류별로 분기
					switch (type) {
					case XmlPullParser.START_TAG:
						/** 원하는 종류의 시작태그를 만났을 때, 값을 추출 */
						if (tag.equals("totalArticleCount")) {
							parser.next();
							brandArr = new String[Integer.parseInt(parser.getText()) + 1];
							brandArr[0] = "브랜드(전체)";
						} else if (tag.equals("keyWord")) {
							parser.next();
							keyWord = parser.getText().trim();
						} else if (tag.equals("idBrandValue")) {
							parser.next();
							idBrandValue = parser.getText();
						}
						
						break;

					case XmlPullParser.END_TAG:
						if (tag.equals("item")) {
							brandArr[count] = idBrandValue;
							
							if (idBrandValue.equals(brandTitle)) {
								spinnerIndex = count;
							}
							
							count++;
						}
						break;
					}

					// 다음 태그로 이동하고, 상태값을 변경
					type = parser.next();
				}

			} catch (XmlPullParserException e) {
				System.out.println("파서 생성 실패 >> " + e.toString());
			} catch (IOException e) {
				System.out.println("파서 읽기 실패 >> " + e.toString());
			}
			
			return result;
		}

		@Override
		protected void onProgressUpdate(String... param) {
		}

		@Override
		protected void onPostExecute(Object param) {
			ArrayAdapter<String> filter_adapter = new ArrayAdapter<String>(ProductFilter.this, R.layout.spinner_item_filter, brandArr);
			filter_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinnerFilter.setAdapter(filter_adapter);
			
			String[] keyWordTemp = null;
			if (keyWord != null) {
				keyWordTemp = keyWord.split(",");
				keyWordArr = new String[keyWordTemp.length];
				checked = new boolean[keyWordTemp.length];
				for (int i=0; i<keyWordTemp.length; i++) {
					keyWordArr[i] = keyWordTemp[i];
				}
			}
			
			boolean row = true;
			LinearLayout item = new LinearLayout(ProductFilter.this);
			
			Display display = getWindowManager().getDefaultDisplay();
			Point size = new Point();
			display.getSize(size);
			int my_width = size.x;
			
			int check_width = my_width / 4;
			
			if (keyWordArr != null) {
				for (int i=0; i<keyWordArr.length; i++) {
					if (i % 4 == 0) {
						item = new LinearLayout(ProductFilter.this);
					}
					LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
					params.bottomMargin = 15;
					final CheckBox cb = new CheckBox(ProductFilter.this);
					cb.setLayoutParams(params);
					cb.setText(keyWordArr[i]);
					cb.setTextSize(12);
					cb.setWidth(check_width);
					cb.setTextColor(Color.parseColor("#7c7c7c"));
					cb.setButtonDrawable(new StateListDrawable());
					cb.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							boolean isCh = cb.isChecked();
							if (isCh) {
								cb.setTextColor(Color.parseColor("#e63646"));
							} else {
								cb.setTextColor(Color.parseColor("#7c7c7c"));
							}
						}
					});
					
					if (paramKeyWordArr != null) {
						for (int j=0; j<paramKeyWordArr.length; j++) {
							if (paramKeyWordArr[j].equals(keyWordArr[i])) {
								cb.setChecked(true);
								checked[i] = true;
								cb.setTextColor(Color.parseColor("#e63646"));
							}
						}
					}
					
					final int index = i;
					cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
						@Override
						public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
							if (isChecked) {
								checked[index] = true;
							} else {
								checked[index] = false;
							}
						}
					});
					item.addView(cb);
					
					if (i % 4 == 3) {
						keyWordLayout.addView(item);
						row = false;
					} else {
						row = true;
					}
				}
			}
			
			if (row) {
				keyWordLayout.addView(item);
			}
			
			if (spinnerIndex > 0) {
				spinnerFilter.setSelection(spinnerIndex);
			}
			CDialog.hideLoading();
		}
		
		@Override
		protected void onCancelled() {
			CDialog.hideLoading();
			AlertDialog.Builder alert = new AlertDialog.Builder(new ContextThemeWrapper(ProductFilter.this, android.R.style.Theme_Holo_Light_Dialog));
			alert.setMessage("일시적인 통신에러입니다.");
			alert.setCancelable(false);
			alert.setPositiveButton("다시 시도", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					(new FilterWorker()).execute();
				}
			});
			alert.setNegativeButton("뒤로 가기", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
			alert.create();
			alert.show();
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		switch(arg0.getId()) {
		case R.id.spinnerFilter:
			if (arg2 == 0) {
				brandTitle = "";
			} else {
				brandTitle = brandArr[arg2].trim();
			}
			break;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.okBt:
			String price1Value = price1.getText().toString().trim();
			String price2Value = price2.getText().toString().trim();
			
			if (price1Value.length() > 9 || price2Value.length() > 9) {
				Toast.makeText(this, "가격은 9글자까지만 입력이 가능합니다.", Toast.LENGTH_SHORT).show();
				return;
			}
			
			String keyWordValue = "";
			boolean keyWordCheck = false;
			
			if (orderRadioGroup.getCheckedRadioButtonId() == R.id.orderBt1) {
				paramOrder = 0;
			} else if (orderRadioGroup.getCheckedRadioButtonId() == R.id.orderBt2) {
				paramOrder = 1;
			} else if (orderRadioGroup.getCheckedRadioButtonId() == R.id.orderBt3) {
				paramOrder = 2;
			} else if (orderRadioGroup.getCheckedRadioButtonId() == R.id.orderBt4) {
				paramOrder = 3;
			} else if (orderRadioGroup.getCheckedRadioButtonId() == R.id.orderBt5) {
				paramOrder = 4;
			}
			
			for (int i=0; i<keyWordArr.length; i++) {
				if (checked[i]) {
					keyWordValue += keyWordArr[i] + ",";
					keyWordCheck = true;
				}
			}
			
			if (keyWordCheck) {
				keyWordValue = keyWordValue.substring(0, keyWordValue.length() - 1);
			}
			
			if (newFilter) {
				Intent intent = new Intent();
				
				intent.putExtra("PARAM_id", paramId);
				intent.putExtra("PARAM_first", paramFirst);
				intent.putExtra("PARAM_title", paramTitle);
				intent.putExtra("PARAM_total", paramTotal);
				
				intent.putExtra("PARAM_filter", 1);
				intent.putExtra("PARAM_order", paramOrder);
				intent.putExtra("PARAM_brand", brandTitle);
				intent.putExtra("PARAM_price1", price1Value);
				intent.putExtra("PARAM_price2", price2Value);
				intent.putExtra("PARAM_keyWord", keyWordValue);
				
				setResult(Activity.RESULT_OK, intent);
				
				finish();
			} else {
				Intent tent = new Intent(this, ListCategoryProduct.class);
				tent.putExtra("PARAM_id", paramId);
				tent.putExtra("PARAM_first", paramFirst);
				tent.putExtra("PARAM_title", paramTitle);
				tent.putExtra("PARAM_total", paramTotal);
				
				tent.putExtra("PARAM_filter", 1);
				tent.putExtra("PARAM_order", paramOrder);
				tent.putExtra("PARAM_brand", brandTitle);
				tent.putExtra("PARAM_price1", price1Value);
				tent.putExtra("PARAM_price2", price2Value);
				tent.putExtra("PARAM_keyWord", keyWordValue);
				tent.putExtra("PARAM_newFilter", true);
				
				startActivity(tent);
			}
			
			break;
			
		case R.id.orderBt1:
			orderBt1.setTextColor(Color.parseColor("#e63646"));
			orderBt2.setTextColor(Color.parseColor("#252525"));
			orderBt3.setTextColor(Color.parseColor("#252525"));
			orderBt4.setTextColor(Color.parseColor("#252525"));
			orderBt5.setTextColor(Color.parseColor("#252525"));
			break;
			
		case R.id.orderBt2:
			orderBt2.setTextColor(Color.parseColor("#e63646"));
			orderBt1.setTextColor(Color.parseColor("#252525"));
			orderBt3.setTextColor(Color.parseColor("#252525"));
			orderBt4.setTextColor(Color.parseColor("#252525"));
			orderBt5.setTextColor(Color.parseColor("#252525"));
			break;
			
		case R.id.orderBt3:
			orderBt3.setTextColor(Color.parseColor("#e63646"));
			orderBt1.setTextColor(Color.parseColor("#252525"));
			orderBt2.setTextColor(Color.parseColor("#252525"));
			orderBt4.setTextColor(Color.parseColor("#252525"));
			orderBt5.setTextColor(Color.parseColor("#252525"));
			break;
			
		case R.id.orderBt4:
			orderBt4.setTextColor(Color.parseColor("#e63646"));
			orderBt1.setTextColor(Color.parseColor("#252525"));
			orderBt2.setTextColor(Color.parseColor("#252525"));
			orderBt3.setTextColor(Color.parseColor("#252525"));
			orderBt5.setTextColor(Color.parseColor("#252525"));
			break;
			
		case R.id.orderBt5:
			orderBt5.setTextColor(Color.parseColor("#e63646"));
			orderBt1.setTextColor(Color.parseColor("#252525"));
			orderBt2.setTextColor(Color.parseColor("#252525"));
			orderBt3.setTextColor(Color.parseColor("#252525"));
			orderBt4.setTextColor(Color.parseColor("#252525"));
			break;
		}
	}
	
    @Override
	protected void onDestroy() {
		super.onDestroy();
		am.removeActivity(this);
	}

}
